<?php
// session.php
// 2005-2008 Derek "Kazan" Meek
// used by permission

class session
{
	var $app;
	var $uid;
	var $username;
	var $access_level; // 0 not logged in, 1 default logged in, higher values custom
	var $session_name;
	var $session_var;
	
	function __construct($session_name, $app)
	{ 
		session_name($session_name);
		session_start();
		session_register(); 
		$this->app =& $app; 
		$this->session_name = $session_name;
		$this->session_var =& $_SESSION[$this->session_name];
		
		$this->uid = ifemptyuse($this->session_var['user']['user_id'], 0); 
		$this->username = $this->session_var['user']['username']; 
		$this->access_level = ifemptyuse($this->session_var['user']['access_level'], 0);
	}
	
	function get_user_id()
	{
		return ifemptyuse($this->session_var['user']['user_id'], 0);
	}
	
	function isLoggedIn()
	{
		return !empty($this->session_var['user']['user_id']);
	}
	
	function reset_session()
	{
		$this->session_var = 0;
		$this->uid = 0;
		$this->username = "";
		$this->access_level = 0;
	}

	// returns true on succes
	function login($username, $password)
	{
		global $config;
		switch ($config['auth_type'])
		{
			case 'db';
				$login_func = "db_login";
				break;
				
			case 'ldap':
				if ($config['LDAP']['type'] == 'AD')
					$login_func = "ldap_ad_login";
				else
					$login_func = "ldap_open_login";
				break;
		}
		
		$success = $this->$login_func($username, $password);
		if ($success)
		{
			$this->session_var = array();
			//$this->session_var['user'] = array();
			$this->session_var['user']['user_id'] = $this->uid; 
			$this->session_var['user']['username'] = $this->username; 
			$this->session_var['user']['access_level'] = $this->access_level;
			return true;
		}
		return false;
	}
			
	function db_login($username, $password)
	{
		$pass_hash = md5($password);
		$sql =	"SELECT * FROM `users` WHERE `username`='" . $this->app->db->real_escape($username) 
					. "' AND `pass`='" . $this->app->db->real_escape($pass_hash)  . "'";
		$res = $this->app->db->query($sql);
		if (!$res) return false;
		
		if ($this->app->db->num_rows($res) != 1)
		{
			return false;
		}
		$db_user = $this->app->db->fetch_assoc($res);
		$this->app->db->free_result($res);
		
		$this->uid = $db_user['user_id'];
		$this->username = $db_user['username'];
		$this->access_level = $db_user['access_level'];
		return true;
	}
	
	function ldap_open_login($username, $password)
	{
		die("Unimplemented function ldap_open_login");
	}
	
	function ldap_ad_login($username, $password)
	{
		global $config;
		
		// connect to server
		$ldap_conn = ldap_connect($config['LDAP']['Server']) or trigger_error("Could not connect to LDAP server");
		
		// attempt to bind as our proxy user
		$bind_res = ldap_bind($ldap_conn, $config['LDAP']['User'], $config['LDAP']['Pass']) or trigger_error("Could not bind to LDAP server");

		// search for the real user
		$srch = ldap_search($ldap_conn, $config['LDAP']['base_dn'], 
					"(&(objectClass=user)(&(SAMAccountName=$username)(!(displayName=*SystemMailbox*))))",
					array("dn","cn","mail","displayName"));
		$res = ldap_get_entries($ldap_conn, $srch);
		if ($res['count'] == 0)
		{
			return false;
		}
		else if ($res['count'] > 1)
		{
			trigger_error("Incorrect number of LDAP results: " . $res['count']);
		}
		
		// try to bind as the real user
		$bind_res = @ldap_bind($ldap_conn, $res[0]['dn'], $password);
		
		if (!$bind_res)
		{
			// bind failed, incorrect password		
			return false;
		}
		// bind succeeded, check local user table, update as appropriate
		//echo("<pre>");
		//print_r($res);
		//echo("<pre>");
		$dn = $res[0]['dn'];
		$dispname = $res[0]['displayname'][0];
		$email = $res[0]['mail'][0];
		
		$db_user = $this->get_user_bydn($dn);
		if ($db_user === false)
		{
			$this->username = $username;
			$this->access_level = 1;
			$this->uid = $this->create_user_ldap($username, $dispname, $email, $dn);
		}
		else
		{
			$this->uid = $db_user['user_id'];
			$this->username = $db_user['username'];
			$this->access_level = $db_user['access_level'];
		}
		return true;
	}
	
	function create_user_ldap($username, $realname, $email, $user_dn)
	{		
		
		$values = array();
		foreach(func_get_args() as $val)
		{
			$values[] = "'" . $this->app->db->real_escape($val) . "'";
		}
		$sql = "INSERT INTO `users` (`username`,`realname`,`email`,`ldap_dn`) VALUES(";
		$sql .= implode(",", $values);
		$sql .= ")";
		return $this->app->db->insertid($sql);
	}
	
	function get_user_bydn($user_dn)
	{
		$sql =	"SELECT * FROM `users` WHERE `ldap_dn`='" . $this->app->db->real_escape($user_dn) . "'";
		$res = $this->app->db->query($sql);
		if (!$res) return false;
		
		if ($this->app->db->num_rows($res) != 1)
		{
			return false;
		}
		$user = $this->app->db->fetch_assoc($res);
		$this->app->db->free_result($res);
		return $user;
	}
	
	function get_user($username)
	{
		$sql =	"SELECT * FROM `users` WHERE `username`='" . $this->app->db->real_escape($username) . "'";
		$res = $this->app->db->query($sql);
		if (!$res) return false;
		if ($this->app->db->num_rows($res) != 1)
		{
			return false;
		}
		$user = $this->app->db->fetch_assoc($res);
		$this->app->db->free_result($res);
		return $user;
	}
	
	function get_user_byid($user_id)
	{
		$sql =	"SELECT * FROM `users` WHERE `user_id`='" . $this->app->db->real_escape($user_id) . "'";
		$res = $this->app->db->query($sql);
		if (!$res) return false;
		if ($this->app->db->num_rows($res) != 1)
		{
			return false;
		}
		$user = $this->app->db->fetch_assoc($res);
		$this->app->db->free_result($res);
		return $user;
	}
	
	function get_users($start, $end)
	{
		
		$l = $this->app->db->real_escape($end);
		$o = $this->app->db->real_escape($start);
		$sql =	"SELECT user_id,username,realname,email,access_level FROM `users` LIMIT $l OFFSET $o";
		$res = $this->app->db->query($sql);
		
		$retval = array();
		while ($user = $this->app->db->fetch_assoc($res))
			$retval[] = $user;
		$this->app->db->free_result($res);
		
		return $retval;
	}
	
	function user_count()
	{
		$sql = "SELECT count(*) as cnt FROM `users`";
		$res = $this->app->db->query($sql);
		$row = $this->app->db->fetch_assoc($res);
		$this->app->db->free_result($res);
		return $row['cnt'];
	}
	
	function change_user_access($user_id, $access_level)
	{
		$u = $this->app->db->real_escape($user_id);
		$a = $this->app->db->real_escape($access_level);
		$sql = "UPDATE `users` SET `access_level`=$a WHERE `user_id`=$u";
		$this->app->db->query($sql);
	}
}

?>